package com.xsmart.goods.services;

import com.baomidou.mybatisplus.plugins.Page;
import com.xsmart.common.constant.ResultConstant;
import com.xsmart.common.entity.RequestBean;
import com.xsmart.common.entity.ResponseBean;
import com.xsmart.goods.dao.GoodsManageDao;
import org.apache.commons.collections.map.HashedMap;
import org.omg.PortableServer.LIFESPAN_POLICY_ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.transform.Result;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author xuqinyuan
 */
@Service
public class GoodsManageService {
    @Autowired
    GoodsManageDao goodsManageDao;
    /**
     * 查询商品信息
     * @param requestBean
     * @return
     */
    public ResponseBean queryGoods(RequestBean requestBean){
        ResponseBean responseBean=requestBean.getResponseBean();
        int currentPage=requestBean.getRequestParamInteger("currentPage",1);
        int pageSize=requestBean.getRequestParamInteger("pageSize",10);
        Integer goodsId=requestBean.getRequestParamInteger("goods_id");
        String goodsSn=requestBean.getRequestParamString("goods_sn");
        String goodsName=requestBean.getRequestParamString("goods_name");
        Integer sellerId = requestBean.getRequestParamInteger("sellerId");
        Map<String, Object> goodsMap=new HashMap<>();
        goodsMap.put("goods_id",goodsId);
        goodsMap.put("goods_sn",goodsSn);
        goodsMap.put("goods_name",goodsName);
        goodsMap.put("sellerId", sellerId);
        Page<Map<String,Object>> page=new Page<>(currentPage,pageSize);
        page.setRecords(goodsManageDao.queryGoods(page,goodsMap));
        responseBean.addResultPageItem("goodsManage",page);
        responseBean.setResult(ResultConstant.SUCCESS);
        return  responseBean;
    }

    public ResponseBean queryGoodsSingle(RequestBean requestBean){
        ResponseBean responseBean=requestBean.getResponseBean();
        int currentPage=requestBean.getRequestParamInteger("currentPage",1);
        int pageSize=requestBean.getRequestParamInteger("pageSize",10);
        Integer goodsId=requestBean.getRequestParamInteger("goods_id");
        Page<Map<String,Object>> page=new Page<>(currentPage,pageSize);
        page.setRecords(goodsManageDao.queryGoodsSingle(page,goodsId));
        responseBean.addResultPageItem("goodsManage",page);
        responseBean.setResult(ResultConstant.SUCCESS);
        return  responseBean;
    }

    /**
     * 查询开启状态的店铺
     * @param requestBean
     * @return
     */
    public ResponseBean queryShopList(RequestBean requestBean){
        ResponseBean responseBean = requestBean.getResponseBean();
        String content = requestBean.getRequestParamString("content");
        Integer userId = requestBean.getRequestParamInteger("user_id");
        Map<String, Object> shopMap = new HashMap<>();
        shopMap.put("user_id", userId);
        shopMap.put("content", content);
        List<Map<String, Object>> shopList = goodsManageDao.queryShopList(shopMap);
        responseBean.addResultItem("shopList", shopList);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }


    /**
     * 发布商品
     * @param requestBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean addGoods(RequestBean requestBean){
        ResponseBean responseBean=requestBean.getResponseBean();
        int currentPage=requestBean.getRequestParamInteger("currentPage",1);
        int pageSize=requestBean.getRequestParamInteger("pageSize",10);
        List<String> goodsPhotoList = (List<String>) requestBean.getRequestParam("goods_photo");
        String catIdString =   requestBean.getRequestParamString("category");
        catIdString = catIdString.substring(1, catIdString.length()-1).replace(" ", "");
        Map<String, Object> goodsMap = getParam(requestBean);
        Integer goods_id = goodsManageDao.queryMaxId();
        goods_id = goods_id + 1;
        goodsMap.put("goods_id",goods_id);
        goodsMap.put("cat_path_id", ","+catIdString+",");
        try {
            goodsManageDao.addGoods(goodsMap);
            goodsManageDao.addGoodsPhoto(goodsPhotoList,goods_id);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
        }
        Page<Map<String,Object>> page=new Page<>(currentPage,pageSize);
        responseBean.addResultPageItem("goodsManage",page);
        return  responseBean;
    }

    /**
     * 修改商品信息
     * @param requestBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean modGoods(RequestBean requestBean) {
        int currentPage=requestBean.getRequestParamInteger("currentPage",1);
        int pageSize=requestBean.getRequestParamInteger("pageSize",10);
        ResponseBean responseBean = requestBean.getResponseBean();
        Map<String, Object> goodsMap = getParam(requestBean);
        Integer mod_count = Integer.valueOf(goodsMap.get("mod_count").toString()) + 1;
        Integer goods_id = Integer.valueOf(goodsMap.get("goods_id").toString());
        List<String> goodsPhotoList = (List<String>) requestBean.getRequestParam("goods_photo");
        if (mod_count > 1){
            String goods_sn = goodsMap.get("goods_sn").toString();
            int n = goods_sn.lastIndexOf("-");
            goods_sn = goods_sn.substring(0,n+1) + mod_count;
            goodsMap.put("goods_sn",goods_sn);
        }else {
            String goods_sn = goodsMap.get("goods_sn").toString() + "-" + mod_count;
            goodsMap.put("goods_sn",goods_sn);
        }
        goodsMap.put("mod_count",mod_count);
        try {
            goodsManageDao.addGoodsHis(goods_id);
            goodsManageDao.modGoods(goodsMap);
            goodsManageDao.delGoodsPhoto(goods_id);
            goodsManageDao.addGoodsPhoto(goodsPhotoList,goods_id);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
        }
        //属性添加至具体的商品属性表
        List<Integer> attrId=(List<Integer>)requestBean.getRequestParam("attrId");

        List<Object> color=(List<Object>)requestBean.getRequestParam("color");
        Map<String,Object> colorMap=new HashMap<String,Object>();
        if (color.size()>0){
            for (Object list :color){
                List<String> listOfListType=(List<String>)list;
                colorMap.put(listOfListType.get(0),listOfListType.get(1));

            }
        }

        Map<String,Object>goodMap= new HashMap<>();
        try{
            goodsManageDao.deleteGoodsAttr(goods_id);
            goodMap.put("goods_id",goods_id);
            goodMap.put("user_id",goodsMap.get("user_id").toString());
            for(int i=0;i<attrId.size();i++){
                goodMap.put("attr_id",attrId.get(i));
                String attrValue=requestBean.getRequestParamString(attrId.get(i).toString());
                if(attrValue!=null){
                    goodMap.put("attr_value",attrValue.substring(1,attrValue.length()-1));
                    goodMap.put("color_value",colorMap.get("color"+attrId.get(i)).toString());
                    goodsManageDao.addGoodsAttr(goodMap);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }


        Page<Map<String,Object>> page=new Page<>(currentPage,pageSize);
        responseBean.addResultPageItem("goodsManage",page);
        return responseBean;
    }

    /**
     * 更改商品的状态
     * @param requestBean
     * @return
     */
    public ResponseBean changeOnsale(RequestBean requestBean){
        ResponseBean responseBean = requestBean.getResponseBean();
        String isOnSale = requestBean.getRequestParamString("isOnSale");
        Integer goodsId = requestBean.getRequestParamInteger("goodsId");
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("isOnSale",isOnSale);
        paramMap.put("goodsId",goodsId);
        int num = goodsManageDao.changeOnsale(paramMap);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    public ResponseBean queryGoodComments(RequestBean requestBean){
        ResponseBean responseBean=requestBean.getResponseBean();
        int currentPage=requestBean.getRequestParamInteger("currentPage",1);
        int pageSize=requestBean.getRequestParamInteger("pageSize",10);
        Integer goodsId=requestBean.getRequestParamInteger("goods_id");
        Integer ogaGoods=requestBean.getRequestParamInteger("oga_goods");
        Page<Map<String,Object>> page=new Page<>(currentPage,pageSize);
        page.setRecords(goodsManageDao.queryGoodComments(page,goodsId,ogaGoods));
        responseBean.addResultPageItem("goodsManage",page);
        responseBean.setResult(ResultConstant.SUCCESS);
        return  responseBean;
    }

    public ResponseBean queryMidComments(RequestBean requestBean){
        ResponseBean responseBean=requestBean.getResponseBean();
        int currentPage=requestBean.getRequestParamInteger("currentPage",1);
        int pageSize=requestBean.getRequestParamInteger("pageSize",10);
        Integer goodsId=requestBean.getRequestParamInteger("goods_id");
        Integer ogaGoods=requestBean.getRequestParamInteger("oga_goods");
        Page<Map<String,Object>> page=new Page<>(currentPage,pageSize);
        page.setRecords(goodsManageDao.queryMidComments(page,goodsId,ogaGoods));
        responseBean.addResultPageItem("goodsManage",page);
        responseBean.setResult(ResultConstant.SUCCESS);
        return  responseBean;
    }


    public ResponseBean queryNativeComments(RequestBean requestBean){
        ResponseBean responseBean=requestBean.getResponseBean();
        int currentPage=requestBean.getRequestParamInteger("currentPage",1);
        int pageSize=requestBean.getRequestParamInteger("pageSize",10);
        Integer goodsId=requestBean.getRequestParamInteger("goods_id");
        Integer ogaGoods=requestBean.getRequestParamInteger("oga_goods");
        Page<Map<String,Object>> page=new Page<>(currentPage,pageSize);
        page.setRecords(goodsManageDao.queryNetiveComments(page,goodsId,ogaGoods));
        responseBean.addResultPageItem("goodsManage",page);
        responseBean.setResult(ResultConstant.SUCCESS);
        return  responseBean;
    }


    /**
     * 删除商品
     * @param requestBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean delGoods(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        Integer goods_id = requestBean.getRequestParamInteger("goods_id");
        try {
            goodsManageDao.addGoodsHis(goods_id);
            goodsManageDao.delGoods(goods_id);
            goodsManageDao.delGoodsPhoto(goods_id);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
        }
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 验证商品货号的唯一性
     * @param requestBean
     * @return
     */
    public ResponseBean checkGoodsSn(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        String goods_sn = requestBean.getRequestParamString("goods_sn");
        List<Map<String,Object>> goodsList = goodsManageDao.checkGoodsSn(goods_sn);
        if (goodsList.size() > 0){
            responseBean.setResult(ResultConstant.ERROR);
        }else {
            responseBean.setResult(ResultConstant.SUCCESS);
        }
        return responseBean;
    }

    /**
     * 查询商家信息
     * @param requestBean
     * @return
     */
    public ResponseBean querySellerShop(RequestBean requestBean){
        ResponseBean responseBean = requestBean.getResponseBean();
        List<Map<String,Object>> sellerShopList = goodsManageDao.querySellerShop();
        responseBean.addResultItem("sellerShopList",sellerShopList);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 查询商品的相册
     * @param requestBean
     * @return
     */
    public ResponseBean queryGoodsPhoto(RequestBean requestBean){
        ResponseBean responseBean = requestBean.getResponseBean();
        Integer goods_id = requestBean.getRequestParamInteger("goods_id");
        List<Map<String,Object>> goodsPhotoList = goodsManageDao.queryGoodsPhoto(goods_id);
        responseBean.addResultItem("goodsPhotoList",goodsPhotoList);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 获取参数
     * @param requestBean
     * @return
     */
    private Map<String, Object> getParam(RequestBean requestBean){

        SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String strDate = sfDate.format(new Date());
        System.out.println(strDate);
        Map<String, Object> goodsMap = new HashMap<>();
        List<Integer> catList = (List<Integer>) requestBean.getRequestParam("cat_id");
        List<Integer> brandList = (List<Integer>) requestBean.getRequestParam("brand_id");
        List<Integer> goodsTypeList = (List<Integer>) requestBean.getRequestParam("goods_type");
        List<Integer> sellerShopList = (List<Integer>) requestBean.getRequestParam("from_seller_id");

        if (catList != null && catList.size()>0){
            Integer catId = catList.get(catList.size()-1);
            goodsMap.put("cat_id",catId);
        }
        if (brandList != null && brandList.size()>0){
            Integer brandId = brandList.get(brandList.size()-1);
            goodsMap.put("brand_id",brandId);
        }
        if (goodsTypeList != null && goodsTypeList.size()>0){
            Integer goodsType = goodsTypeList.get(goodsTypeList.size()-1);
            goodsMap.put("goods_type",goodsType);
        }
        if (sellerShopList != null && sellerShopList.size()>0){
            Integer fromSellerId = sellerShopList.get(sellerShopList.size()-1);
            goodsMap.put("from_seller_id",fromSellerId);
        }
        String[][] params = new String[][]{
                {"goods_id", ""},
                {"parent_goods_id", "1"},
                {"cost_price", "0.00"},
                {"brand_desc", ""},
                {"click_count", "0"},
//                {"from_seller_id", ""},
                {"give_integral", "0"},
                {"goods_brief", ""},
                {"goods_desc", ""},
                {"goods_img", ""},
                {"goods_number", ""},
//                {"goods_sn", strDate},
                {"goods_tag", ""},
//                {"goods_type", "43"},
                {"goods_weight", "0.000"},
                {"is_alone_sale", "1"},
                {"is_best", "0"},
                {"is_delete", "0"},
                {"is_hot", "0"},
                {"is_new", "0"},
                {"is_on_sale", "0"},
                {"is_promote", "0"},
                {"is_real", "1"},
                {"is_xiangou", "0"},
                {"keywords", ""},
                {"market_price", "0.00"},
                {"measure_unit", ""},
                {"promote_start_date", null},
                {"promote_end_date", null},
                {"rank_integral", "0"},
                {"seller_note", ""},
                {"shop_price", "0.00"},
                {"sort_order", "100"},
                {"supply_price", "0.00"},
                {"warn_number", "1"},
                {"xiangou_start_date", null},
                {"xiangou_end_date", null},
                {"promote_price", "0.00"},
                {"xiangou_num", "0"},
                {"user_id", ""},
                {"mod_count", "0"},
                {"goods_name", ""}};

        for (String[] param : params) {
            Object value = requestBean.getRequestParam(param[0]);
            if (value == null || "".equals(value)) {
                goodsMap.put(param[0], param[1]);
            } else {
                goodsMap.put(param[0], requestBean.getRequestParam(param[0]));
            }
        }

        if ("".equals(requestBean.getRequestParam("goods_sn"))){
            goodsMap.put("goods_sn",strDate);
        }else {
            goodsMap.put("goods_sn",requestBean.getRequestParam("goods_sn"));
        }
        return goodsMap;
    }

    /**
     * 商品列表编辑商品第一步保存数据
     *
     * @author xxf
     * @date 2018/2/22
     * */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean modGoodsCat(RequestBean requestBean){
        ResponseBean responseBean=requestBean.getResponseBean();
        Integer goodsId=requestBean.getRequestParamInteger("goods_id");
        List<Integer> catList = (List<Integer>) requestBean.getRequestParam("category");
        Integer catId=0;
        if (catList != null && catList.size()>0){
            catId = catList.get(catList.size()-1);
        }
        try {
            goodsManageDao.modGoodsCat(goodsId, catId);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 商品列表第二步存储
     * @author xxf
     * @date 2018/2/22
     * */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean modGoodsGI(RequestBean requestBean){
        ResponseBean responseBean=requestBean.getResponseBean();
        Integer goodsId=requestBean.getRequestParamInteger("goods_id");
        Map<String,Object> goodsMap=new HashMap<String,Object>();
        List<Integer> brandList = (List<Integer>) requestBean.getRequestParam("brand_id");
        if (brandList != null && brandList.size()>0){
            Integer brandId = brandList.get(brandList.size()-1);
            goodsMap.put("brand_id",brandId);
        }
        String[][] params = new String[][]{
                {"goods_id", ""},
                {"cost_price", "0.00"},
                {"goods_brief", ""},
                {"goods_desc", ""},
                {"goods_name", ""},
                {"goods_img", ""},
                {"goods_number", ""},
                {"goods_weight", "0.000"},
                {"is_alone_sale", "1"},
                {"is_delete", "0"},
                {"is_on_sale", "1"},
                {"is_real", "1"},
                {"keywords", ""},
                {"market_price", "0.00"},
                {"sort_order", "100"},
                {"supply_price", "0.00"},
                {"shop_price", "0.00"},
                {"warn_number", "1"}};
        for (String[] param : params) {
            Object value = requestBean.getRequestParam(param[0]);
            if (value == null || "".equals(value)) {
                goodsMap.put(param[0], param[1]);
            } else {
                goodsMap.put(param[0], requestBean.getRequestParam(param[0]));
            }
        }
        try{
            goodsManageDao.modGoodsGI(goodsMap);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }

        List<String> goodsPhotoList = (List<String>) requestBean.getRequestParam("goods_photo");
        try{
            goodsManageDao.delGoodsPhoto(goodsId);
            goodsManageDao.addGoodsPhoto(goodsPhotoList,goodsId);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 商品列表第三步存储
     * @author xxf
     * @date 2018/2/22
     * */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean modGoodsSI(RequestBean requestBean){
        ResponseBean responseBean=requestBean.getResponseBean();
        Integer goodsId=requestBean.getRequestParamInteger("goods_id");
        Map<String,Object> goodsMap=new HashMap<>();
        String[][] params = new String[][]{
                {"is_best", "0"},
                {"is_hot", "0"},
                {"is_new", "0"},
                {"is_promote", "0"},
                {"is_xiangou", "0"},
                {"promote_start_date", null},
                {"promote_end_date", null},
                {"promote_price", "0.00"},
                {"xiangou_start_date", null},
                {"xiangou_end_date", null},
                {"xiangou_num", "0"},
        };
        goodsMap.put("goods_id",goodsId);
        for (String[] param : params) {
            Object value = requestBean.getRequestParam(param[0]);
            if (value == null || "".equals(value)) {
                goodsMap.put(param[0], param[1]);
            } else {
                goodsMap.put(param[0], requestBean.getRequestParam(param[0]));
            }
        }
        try {
            goodsManageDao.modGoodSI(goodsMap);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**
     * 商品列表第四步单独存储
     * @author xxf
     * @date 2018/2/22
     * */
    public ResponseBean modGoodsAttr(RequestBean requestBean){
        ResponseBean responseBean=requestBean.getResponseBean();

        Integer goodsId=requestBean.getRequestParamInteger("goods_id");
        Integer userId=requestBean.getRequestParamInteger("user_id");
        List<Integer> attrId=(List<Integer>)requestBean.getRequestParam("attrId");
        List<Object> color=(List<Object>)requestBean.getRequestParam("color");
        Map<String,Object> colorMap=new HashMap<String,Object>();
        if (color.size()>0){
            for (Object list :color){
                List<String> listOfListType=(List<String>)list;
                colorMap.put(listOfListType.get(0),listOfListType.get(1));

            }
        }

        Map<String,Object>goodMap= new HashMap<>();
        try{
            goodsManageDao.deleteGoodsAttr(goodsId);
            goodMap.put("goods_id",goodsId);
            goodMap.put("user_id",userId);
            for(int i=0;i<attrId.size();i++){
                goodMap.put("attr_id",attrId.get(i));
                String attrValue=requestBean.getRequestParamString(attrId.get(i).toString());
                if(attrValue!=null){
                    goodMap.put("attr_value",attrValue.substring(1,attrValue.length()-1));
                    goodMap.put("color_value",colorMap.get("color"+attrId.get(i)).toString());
                    goodsManageDao.addGoodsAttr(goodMap);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }
}
